export class JsonRpc {
  constructor(payload) {
    // 检查 baseURL. 不能为空
    const { Request, baseURL, timeout = 500000, messageError } = payload
    this._messageError = messageError
    this.req = new Request({
      baseURL,
      timeout,
      messageError
    })
  }

  get_session_id() {
    return this.req.constructor._sid
  }

  get_cids_local(cids_odoo) {
    const cids_str = this.req.localStorage.getItem('cid') || ''
    if (cids_str) {
      const cids1 = cids_str.split(',').map(item => Number(item))
      const cids2 = cids1.filter(item => cids_odoo.includes(item))
      if (cids2.length) {
        if (cids1.length > cids2.length) {
          const cids_str2 = cids2.join(',')
          this.req.localStorage.setItem('cid', cids_str2)
        }
        return cids2
      } else {
        this.req.localStorage.removeItem('cid')
        return cids_odoo
      }
    } else {
      return cids_odoo
    }
  }

  set_cids_local(cids) {
    const cids_str = cids.join(',')
    this.req.localStorage.setItem('cid', cids_str)
  }

  async jsoncall(url, payload = {}, kwargs = {}) {
    const url2 = url[0] === '/' ? url : `/${url}`
    // console.log('jsoncall,', url, payload)

    const data = {
      jsonrpc: '2.0',
      method: 'call',
      params: payload,
      id: Math.floor(Math.random() * 1000000000 + 1)
    }

    const response = await this.req.call_post(url2, data)
    // 析构 响应结果 , 返回 result, 抛异常 error

    const res = response.data
    const { result, error } = res
    const { throw_error } = kwargs

    if (error) {
      console.log('odoo response error')
      if (this._messageError && !throw_error) {
        return this._messageError(error)
      } else {
        return Promise.reject(error)
      }
    } else {
      return result
    }
  }
}
